package com.codi.api.controller.h5;

import com.codi.api.security.UserUtil;
import com.codi.api.validation.AccountValidation;
import com.codi.base.config.ConfigurationMgr;
import com.codi.base.exception.BaseException;
import com.codi.base.log.annotation.Loggable;
import com.codi.base.util.ListUtil;
import com.codi.base.util.RandomUtil;
import com.codi.base.util.StringUtil;
import com.codi.base.web.RequestUtils;
import com.codi.base.web.ResponseUtils;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.constant.H5HttpHeaderConstant;
import com.codi.bus.constant.RuleConstant;
import com.codi.bus.core.dao.UserSessionDao;
import com.codi.bus.core.domain.*;
import com.codi.bus.core.resultModel.*;
import com.codi.bus.core.service.*;
import com.codi.bus.core.service.model.BankModel;
import com.codi.bus.core.service.model.NewsModel;
import com.codi.bus.core.service.model.SMSParameter;
import com.codi.bus.core.service.model.ShareTypeModel;
import com.codi.bus.util.VfCodeUsage;
import com.codi.fcloud.ufx.constant.HsConst;
import com.codi.goldlife.external.IntegralServiceApi;
import com.codi.goldlife.external.databean.ResultBean;
import com.codi.message.constant.ErrorConst;
import com.codi.message.constant.ErrorConstant;
import com.codi.message.util.MessageUtil;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 我的相关控制类
 * @Date:2018/3/8 13:47
 */
@RestController
@Slf4j
@RequestMapping("h5/mine")
public class H5MineController {
    @Resource(name = "clientService")
    private ClientService clientService;

    @Resource(name = "lookupService")
    private LookupService lookupService;

    @Autowired
    private AccountValidation accountValidation;

    @Resource(name = "smsService")
    private SMSService smsService;

    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "bankService")
    private BankService bankService;

    @Resource(name = "queryService")
    private QueryService queryService;

    @Autowired
    private BranchBankService branchBankService;

    @Autowired
    private PaperInfoService paperInfoService;

    @Resource(name = "tradeService")
    private TradeService tradeService;

    @Autowired
    private UserSessionDao userSessionDao;

    @Autowired
    private BankLimitService bankLimitService;

    /**
     * 我的-修改账户信息
     *
     * @param address 地址
     * @param addressCode 地址编码
     * @param occupation 职业
     * @param occupationCode 职业编码
     * @param beneficiary 受益人
     * @param owner 拥有者
     * @param selfSustain 自我维持
     * @return
     */
    @PostMapping("modify_client_info")
    @Loggable
    public BaseResult modifyClientInfo(HttpServletRequest request, @RequestParam String address, @RequestParam String addressCode, @RequestParam String occupation,
                                       @RequestParam String occupationCode, @RequestParam String beneficiary, @RequestParam String owner,
                                       @RequestParam boolean selfSustain) {
        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        BaseResult result = new BaseResult();

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }

        // 验证输入
        AccountValidation.validateClient(address, addressCode, occupation, occupationCode, beneficiary, owner, selfSustain);

        // 修改客户资料
        return clientService.modifyClientInfo(userId, address, addressCode, occupation, occupationCode, beneficiary, owner,
            selfSustain);
    }

    @GetMapping("get_client_info")
    @Loggable
    public BaseResult getClientInfo(HttpServletRequest request) {
        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        BaseResult result = new BaseResult();

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }

        return clientService.getClientInfo(userId);
    }

    /**
     * 我的-发送验证码
     * @param request
     * @param mobile 手机号
     * @param applyNo 申请编号
     * @param usage 使用范围
     * @return
     * @throws BaseException
     */
    @PostMapping("sendvcode")
    @Loggable
    public BaseResult sendvcode(HttpServletRequest request, @RequestParam String mobile, @RequestParam String applyNo,
                                @RequestParam(required = false) VfCodeUsage usage) throws BaseException{
        SMSSendResult result = null;

        // 验证输入
        String ip = RequestUtils.getIpAddr(request);
        if (usage == null) {
            usage = VfCodeUsage.ResetTradePasswd;
        }

        // 获取短信发送控制配置
        List<Lookup> lookups = lookupService.getLookups(RuleConstant.RULE_LOOKUP_TYPE_SMSCONF);

        result = accountValidation.validateSendVCode(mobile, ip, applyNo, usage, lookups);

        if (result != null) {
            return result;
        }

        String verifyCode = RandomUtil.getNumRandom(6, true);

        // 限制在开发环境中使用
        Boolean mockSmsVerifyCode = ConfigurationMgr.getInstance()
            .getBoolean(GlobalConstant.CONFIG_MOCK_SMS_VERIFY_CODE, false);
        if (mockSmsVerifyCode) {
            verifyCode = "666666";
        }

        List<SMSParameter> list = new ArrayList<SMSParameter>();
        SMSParameter parameter = new SMSParameter();
        parameter.setKey(GlobalConstant.SMS_PLACEHOLDER_VCODE);
        parameter.setValue(verifyCode);
        list.add(parameter);

        result = smsService.generateSmsMessage(mobile, list);
        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }

        return result;
    }


    /**
     * 我的-检查身份证手机号验证码
     * @param id_card 身份证
     * @param mobile 手机号
     * @param verification_code 验证码
     * @return
     */
    @PostMapping("check_mobile_id_card")
    @Loggable
    public BaseResult checkUserExist(@RequestParam String id_card, @RequestParam String mobile,
                                     @RequestParam String verification_code) {
        BaseResult result = userService.verifyUserIdAndMobile(id_card, mobile, verification_code);

        return result;
    }

    /**
     * 重置交易密码
     * @param request
     * @param id_card 身份证
     * @param mobile 手机号
     * @param verification_code 验证码
     * @param newest_passwd 新密码
     * @return
     * @throws BaseException
     */
    @PostMapping("reset_trade_password")
    @Loggable
    public BaseResult resetTradePassword(HttpServletRequest request, @RequestParam String id_card,
                                         @RequestParam String mobile, @RequestParam String verification_code, @RequestParam String newest_passwd) throws BaseException {
        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        BaseResult result = new BaseResult();

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }

        result = userService.resetTradePassword(userId, id_card, mobile, verification_code,
            newest_passwd);

        return result;
    }

    /**
     * 获取用户名下银行卡列表
     * @param request
     * @return
     */
    @GetMapping("get_bank")
    @Loggable
    public BaseResult getBank(HttpServletRequest request) {
        BaseListResult result = null;

        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }

        // 获取客户编号
        User userEntity = userService.getUser(userId);
        if (userEntity == null) {
            result = new BankListResult();
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);

            return result;
        }

        if (StringUtil.isEmpty(userEntity.getExternalClientId())) {
            result = new BankListResult();
            result.setSuccess(true);
        } else {

            List<UserBank> userBanks = bankService.getListByUserId(userId);

            if (ListUtil.isNotEmpty(userBanks)) {
                result = new BankListResult();
                result.setSuccess(true);

                List<BankModel> banks = new ArrayList<>(userBanks.size());
                userBanks.forEach(bank -> {
                    BankModel bankModel = new BankModel();
                    bankModel.setBranchBank(bank.getBranchbank() == null ? "": bank.getBranchbank());
                    bankModel.setBranchBankName(bank.getBankBranchName() == null ? "": bank.getBankBranchName());
                    bankModel.setBankName(bank.getBankName());
                    bankModel.setBankCode(bank.getBankCode());
                    bankModel.setUserBankNo(bank.getUserBankNo());
                    bankModel.setCapitalMode(bank.getCapitalMode());
                    bankModel.setTradeAccount(bank.getExternalTradeAccount());


                    banks.add(bankModel);
                });

                ((BankListResult) result).setBanks(banks);
            }
        }

        return result;
    }

    @RequestMapping(value = "/getApp", method = RequestMethod.GET)
    @Loggable
    public BaseResult getAppBanks(HttpServletRequest request, HttpServletResponse response) {
        BaseListResult result = null;

        // 获取客户编号
        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }
        User userEntity = userService.getUser(userId);
        if (userEntity == null) {
            result.setSuccess(false);
            result = new BankListResult();
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            ResponseUtils.renderJson(request, response, result, true);
            return result;
        }
        if (StringUtil.isEmpty(userEntity.getExternalClientId())) {
            result = new BankListResult();
            result.setSuccess(true);
        } else {

            List<UserBank> userBanks = bankService.getListByUserId(userId);

            if (ListUtil.isNotEmpty(userBanks)) {
                result = new BankListResult();
                result.setSuccess(true);

                List<BankModel> banks = new ArrayList<>(userBanks.size());
                for (UserBank bank : userBanks){
                    if (GlobalConstant.CAPITAL_MODE_COUNTER.equals(bank.getCapitalMode())){
                        continue;
                    }
                    BankModel bankModel = new BankModel();
                    bankModel.setBranchBank(bank.getBranchbank() == null ? "": bank.getBranchbank());
                    bankModel.setBranchBankName(bank.getBankBranchName() == null ? "": bank.getBankBranchName());
                    bankModel.setBankName(bank.getBankName());
                    bankModel.setBankCode(bank.getBankCode());
                    bankModel.setUserBankNo(bank.getUserBankNo());
                    bankModel.setCapitalMode(bank.getCapitalMode());
                    bankModel.setTradeAccount(bank.getExternalTradeAccount());
                    //查询该银行的限额
                    BankLimit bankLimit = bankLimitService.selectByCodeAndChannel(bank.getBankCode(), bank.getCapitalMode());
                    if (bankLimit != null) {

                        // 单笔限额max
                        if (bankLimit.getSingleLimit() == null || bankLimit.getSingleLimit() == -1) {
                        } else {
                            bankModel.setSingleDealMaxValue(BigDecimal.valueOf(bankLimit.getSingleLimit()));
                        }
                    }
                    banks.add(bankModel);
                }


                ((BankListResult) result).setBanks(banks);
            }
        }

        return result;

    }


    /**
     * 省份
     */
    @GetMapping("bank/province")
    @Loggable
    public BaseResult getProvince(){
        List<String> provinces = branchBankService.getProvince();
        BaseResult result = new BaseResult();
        result.setResult(provinces);
        return result;
    }

    /**
     * 地级市
     */
    @GetMapping("bank/city")
    @Loggable
    public BaseResult getCityByProvince(String provinceName){
        List<String> citys = branchBankService.getCity(provinceName);
        BaseResult result = new BaseResult();
        result.setResult(citys);
        return result;
    }

    /**
     * 一个市的一种银行
     */
    @GetMapping("bank/cityBank")
    @Loggable
    public BaseResult getBankByCity(String cityName, String bankName){
        List<BankName> cityBanks = branchBankService.getCityBank(cityName, bankName);
        BaseResult result = new BaseResult();
        result.setResult(cityBanks);
        return result;
    }

    /**
     * 搜索支行
     */
    @GetMapping("bank/fundBank")
    @Loggable
    public BaseResult getBankByWord(String bankName, String word){
        List<BankName> fundBanks = branchBankService.getFundBank(bankName, word);
        BaseResult result = new BaseResult();
        result.setResult(fundBanks);
        return result;
    }

    /**
     * 支行修改
     */
    @PostMapping("bank/setBank")
    @Loggable
    public BaseResult setBranchBank(HttpServletRequest request, String vcBranchbank, String vcBankname, String tradePassword){
        BaseResult result = null;
        result = accountValidation.setBranchBankValidate(vcBranchbank,tradePassword);
        if (result != null){
            return result;
        }

        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }

        return branchBankService.setBranchBank(userId, vcBranchbank, vcBankname, tradePassword);
    }

    /**
     * 风险测评-获取问题
     * @param sort_direction
     * @param answer_object
     * @param paper_client_type
     * @return
     */
    @GetMapping("paper/questions")
    @Loggable
    public BaseResult getPaperinfo(@RequestParam(required = false) String sort_direction,
                                   @RequestParam(defaultValue = HsConst.ANSWER_TYPE_PERSON) String answer_object,
                                   @RequestParam(required = false) String paper_client_type) {
        BaseResult result = new BaseResult();

        result.setResult(paperInfoService.queryPaperInfoQuestionsNew(
            new PaperInfoQuestionRequest(sort_direction, answer_object, paper_client_type)));

        return result;
    }

    /**
     * 风险测评-提交风险测评答案
     * 添加profileId
     * @param request
     * @param elig_content
     * @param invest_risk_tolerance
     * @return
     */
    @PostMapping("paper/commit_answer")
    @Loggable
    public BaseResult commitAnswer(HttpServletRequest request, @RequestParam String elig_content,
                                   @RequestParam(required = false) String invest_risk_tolerance, String profileId) {
        BaseResult result = new BaseResult();
        Long pId = null;
        if (profileId != null){
            pId = Long.valueOf(profileId);
        }
        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }

        result.setResult(paperInfoService
            .addOrModifyPaperInfoAcct(userId, elig_content, invest_risk_tolerance,pId));

        return result;
    }

    /**
     * 对风险评测进行了修改
     * 不知道机构是否调用
     * 风险测评-获取测评结果
     * @param request
     * @param password
     * @return
     */
    @GetMapping("paper/test_result")
    @Loggable
    public BaseResult getPaperInfoTestResult(HttpServletRequest request, @RequestParam(required = false) String password) {
        BaseResult result = new BaseResult();

        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }

        result.setResult(paperInfoService.getUserPaperInfoTestResult(userId, password,null));

        return result;
    }

    /**
     * 对风险评测进行了修改
     * 不知道机构是否调用
     * 风险测评-私募获取测评结果
     * @param request
     * @param password
     * @return
     */
    @GetMapping("paper/test-result")
    @Loggable
    public BaseResult getPrivPaperInfoTestResult(HttpServletRequest request, @RequestParam(required = false) String password) {
        BaseResult result = new BaseResult();

        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }

        result.setResult(paperInfoService.getUserPaperInfoTestResult(userId, password,null));

        return result;
    }


    /**
     * 定投管理列表
     * @param request
     * @param requestNum     请求行数
     * @param queryFlag      重新统计总记录数标志
     * @param beginNum       查询起始行号
     * @param sortDirection  返回排序方式 （0:倒序；1：顺序）
     * @return
     */
    @GetMapping("invest/fixes")
    @Loggable
    FixListResult fixes(HttpServletRequest request, @RequestParam Integer requestNum, @RequestParam Integer queryFlag, @RequestParam Integer beginNum,
                     @RequestParam String sortDirection) {
        FixListResult result = new FixListResult();

        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));

            return result;
        }


        return queryService.getFixes(userId, requestNum, queryFlag, beginNum, sortDirection);
    }

    /**
     * 定投管理-银行卡限额
     * @param request
     * @param fundCode 基金代码
     * @param capitalMode 三方渠道
     * @param businCode 业务代码
     * @return
     */
    @GetMapping("invest/limits")
    @Loggable
    public TradeLimitListResult limitQuery(HttpServletRequest request, @RequestParam String fundCode,
                                    @RequestParam String capitalMode,
                                    @RequestParam String businCode) {
        TradeLimitListResult result = new TradeLimitListResult();

        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));
            return result;
        }

        ShareTypeModel shareTypeModel = queryService.getShareType(fundCode);

        if (shareTypeModel == null || StringUtil.isEmpty(shareTypeModel.getShareType())) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_SHARE_TYPE_FIND);
            result.setErrorMessage(MessageUtil.getErrorMessage(ErrorConstant.ERROR_NO_SHARE_TYPE_FIND, null));
            return result;
        }

        String shareType = shareTypeModel.getShareType();

        User user = userService.getUser(userId);
        String custType = user.getIsOrg() ? GlobalConstant.CUST_TYPE_ORGANIZATION : GlobalConstant.CUST_TYPE_PERSONAL;
        result = queryService.queryTradeLimits(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", fundCode, shareType,
            capitalMode, businCode, custType);

        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }

        return result;
    }


    @GetMapping("invest/getBank")
    @Loggable
    public BaseListResult getBanks(HttpServletRequest request) {
        BaseListResult result = new BaseListResult();

        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));
            return result;
        }

        // 获取客户编号
        User userEntity = userService.getUser(userId);

        if (userEntity == null) {
            result = new BankListResult();
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);

            return result;
        }
        if (StringUtil.isEmpty(userEntity.getExternalClientId())) {
            result = new BankListResult();
            result.setSuccess(true);
        } else {



            List<UserBank> userBanks = bankService.getListByUserId(userId);

            if (ListUtil.isNotEmpty(userBanks)) {
                result = new BankListResult();
                result.setSuccess(true);

                List<BankModel> banks = new ArrayList<>(userBanks.size());
                userBanks.forEach(bank -> {
                    BankModel bankModel = new BankModel();
                    bankModel.setBranchBank(bank.getBranchbank() == null ? "": bank.getBranchbank());
                    bankModel.setBranchBankName(bank.getBankBranchName() == null ? "": bank.getBankBranchName());
                    bankModel.setBankName(bank.getBankName());
                    bankModel.setBankCode(bank.getBankCode());
                    bankModel.setUserBankNo(bank.getUserBankNo());
                    bankModel.setCapitalMode(bank.getCapitalMode());
                    bankModel.setTradeAccount(bank.getExternalTradeAccount());


                    banks.add(bankModel);
                });

                ((BankListResult) result).setBanks(banks);
            }
        }

        return result;
    }


    @PostMapping("invest/modifyfix")
    @Loggable
    public BaseResult modifyFix(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam String tradePassword, @RequestParam boolean checkRisk,
                                @RequestParam String protocolPeriodUnit, @RequestParam String applyNo, @RequestParam String bankAccount,
                                @RequestParam String paymentType, @RequestParam String fundName, @RequestParam String fundCode,
                                @RequestParam BigDecimal balance, @RequestParam String scheduledProtocolId, @RequestParam String fixModel,
                                @RequestParam Long protocolFixDay, @RequestParam String expiryDate) {
        BaseResult result = null;

        Long userId = null;

        if (! Strings.isNullOrEmpty(request.getHeader("userId"))) {
            userId = Long.valueOf(request.getHeader("userId").trim());
        }

        if (userId == null) {
            result = new BaseResult();
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_USER_FIND);
            result.setErrorMessage(MessageUtil.getErrorMsg(ErrorConstant.ERROR_NO_USER_FIND));
            return result;
        }

        // 机构用户不能定投
        User user = userService.getUser(userId);
        if (user.getIsOrg()) {
            result = new BaseResult();
            result.setSuccess(false)
                .setErrorCode(ErrorConst.COMMON_USER_PERMISSION_ONLY)
                .setErrorMessage(MessageUtil.getErrorMsg(ErrorConst.COMMON_USER_PERMISSION_ONLY));


            return result;
        }

        // 定投协议号不能为空
        if (StringUtil.isEmpty(scheduledProtocolId)) {
            result = new BaseResult();
            result.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
            result.setErrorCode(ErrorConstant.ERROR_FIELD_NO_FIND);
            Map<String, String> map = new HashMap<>();
            map.put(ErrorConstant.PLACEHOLDER_FIELD_NO_FIND_FIELD, "定投协议号");
            result.setErrorMessage(MessageUtil.getErrorMessage(ErrorConstant.ERROR_FIELD_NO_FIND, map));

            return result;
        }

        // 检查基金的风险等级和用户的等级
        if (checkRisk && invalidRisk(request, response, fundCode, userId)) {
            result = new BaseResult();
            result.setSuccess(false);
            result.setErrorMessage("基金的风险等级和用户的等级不匹配!");

            return result;
        }

        // 获取份额类别
        ShareTypeModel shareTypeModel = queryService.getShareType(fundCode);
        if (shareTypeModel == null || StringUtil.isEmpty(shareTypeModel.getShareType())) {
            result = new BaseResult();
            result.setSuccess(false);
            result.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
            result.setErrorCode(ErrorConstant.ERROR_NO_SHARE_TYPE_FIND);
            result.setErrorMessage(MessageUtil.getErrorMessage(ErrorConstant.ERROR_NO_SHARE_TYPE_FIND, null));

            return result;
        }

        String shareType = shareTypeModel.getShareType(); // 份额类别
        String token = userSessionDao.getEntityByUserId(userId).getToken();

        // 调用接口
        result = tradeService.fix(applyNo, tradePassword, protocolFixDay, shareType, bankAccount, fundName,
            protocolPeriodUnit, userId, balance, fundCode, paymentType, token, fixModel, scheduledProtocolId,
            expiryDate);
        if (!result.getSuccess() && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }


        return result;
    }


    /**
     * 对风险评测进行了修改
     * 不知道机构是否调用
     * 检查风险等级是否和用户的匹配
     *
     * @param request
     * @param response
     * @param fundCode

     * @return
     */

    private boolean invalidRisk(HttpServletRequest request, HttpServletResponse response, String fundCode,
                                Long userId) {
        BaseResult result;
        NewsModel fundRiskLevel = queryService.getRiskLevel(fundCode);
        PaperInfoTestResult testResult = paperInfoService.getUserPaperInfoTestResult(userId,
            "",null);
        Integer investRiskLevel = 0;
        if (!StringUtil.isEmpty(testResult.getInvest_risk_tolerance())) {
            investRiskLevel = Integer.parseInt(testResult.getInvest_risk_tolerance());
        }

        // 基金的风险等级大于用户的投资风险等级
        /*进取型5,成长型4,平衡型3,稳健型2,保守型1
          高风险5,中高风险4,中风险3,中低风险2,低风险1*/
        if (investRiskLevel < fundRiskLevel.getRiskLevel()) {
            result = new BaseResult();
            result.setSuccess(false);
            result.setErrorType(GlobalConstant.ERROR_TYPE_BUSINESS);
            result.setErrorCode(ErrorConstant.ERROR_RISK_LEVEL);
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
            ResponseUtils.renderJson(request, response, result, true);
            return true;
        }
        return false;
    }
}
